import React, {Component} from 'react';
import {
    Dimensions,
    Image,
    StyleSheet,
    Text,
    TextInput,
    TouchableOpacity,
    View,
    ScrollView
} from 'react-native';
import StorageUtil           from '../utils/StorageUtil';
import ListItemDivider       from '../views/ListItemDivider.js';
import LoadingView           from '../views/LoadingView';
import *as BaseAPI           from '../utils/BaseAPI';
import  VerifyCode           from 'react-native-verify-code';
import  DeviceInfo           from 'react-native-device-info';
import Toast, {DURATION}     from 'react-native-easy-toast';
import {NavigationActions}   from 'react-navigation';
import  LinearGradient       from 'react-native-linear-gradient';
import Utils                 from '../utils/utils';
const {width} = Dimensions.get('window');

export default class LoginScreen extends Component {
    constructor(props) {
        super(props);
        this.state = {
            inputUsername: '',
            phone: '',
            code: '',
            showProgress:false
        };
    }

    startCountdown = ()=>{
        // 获取短信数据
        this.requestSMSCode();
    }

    onValueChange = (text)=>{
        this.setState({code:text.trim()});
    }

    // componentWillUnmount() {
    //     this.timer && clearTimeout(this.timer);
    // }

    beforeCountdown = ()=>{
        // 手机号
        var phoneStr = this.state.phone;
        if (!phoneStr.length) {
            this.refs.toast.show('手机号不能为空');
            return false;
        } else if (!Utils.isPhoneAvailable(phoneStr)) {
            this.refs.toast.show('手机号不正确');
            return false;
        } else {
            return true;
        }
    }

    requestSMSCode(){
        // this.setState({showProgress:true});
        fetch(BaseAPI.GetCodeUrl+this.state.phone, {
            method:'GET'
        }).then((res)=>res.json())
            .then((json)=>{

                console.log('短信收到'+ json + JSON.stringify(json));

                // this.setState({showProgress:false});
                if (json.ret === 0 ) {
                    this.refs.toast.show('短信已发送,请注意查收');
                }
                else {
                    this.refs.toast.show('短信获取失败,请过段时间重新获取');
                }
            })
            .catch((e)=>{

                console.log('短信失败'+ e + JSON.stringify(e));

                this.setState({showProgress:false});
                // // 网络错误
                this.refs.toast.show('网络请求出错：' + e);
            })
    }


    goLogin(){
        // http://sh.realbullgame.com/mobile/authorize?
        // bundleid=com.reallycattle.ccmj&duid=A72CF46B-8031-C070-C66D-751C50B95D2B
        // &gss=101&type=realbullgame&platform=mobile&ver=1.1.224&lang=zh_CNundefined

            var bundleID= DeviceInfo.getBundleId();
            var UniqueID= DeviceInfo.getUniqueID();
            var versionID= DeviceInfo.getVersion();
            var URL=BaseAPI.HostUrl+bundleID+'&duid='+UniqueID
                +'&gss=320&type=appstore&platform=mobile&ver='+versionID+'&lang=zh_CN';

            console.log('本机数据'+ URL);

            fetch(URL, {
                    method:'GET'
                }).then((res)=>res.json())
                    .then((json)=>{
                        this.setState({showProgress:false});
                        console.log('HAHHA登录注册界面'+ json + JSON.stringify(json));
                        if (json.state ===0){


                            // console.log('数据Key'+ json.)
                            this.refs.toast.show('登录成功');
                            StorageUtil.set('hasLogin',{'hasLogin':true});
                            StorageUtil.set('token',{'token':json.token});
                            StorageUtil.set('token',{'token':json.token});
                            StorageUtil.set('token',{'token':json.token});


                            // StorageUtil.set('uid',{'uid':json.user.uid});

                            const resetAction = NavigationActions.reset({
                                index: 0,
                                actions: [
                                    NavigationActions.navigate({routeName: 'Home'})
                                ]
                            });
                            this.props.navigation.dispatch(resetAction);

                        }else {
                            this.refs.toast.show('登录失败');
                        }
                    })
                    .catch((e)=>{
                        console.log('网络请求'+e);

                        this.setState({showProgress:false});
                        // // 网络错误
                        this.refs.toast.show('网络请求出错：' + e);
                    })



    }

    // goLogin(){
    //     this.setState({showProgress:true});
    //     var bundleID= DeviceInfo.getBundleId();
    //     var UniqueID= DeviceInfo.getUniqueID();
    //     var versionID= DeviceInfo.getVersion();
    //     var paramsStr='&bundleid='+bundleID+'&gss=320&duid='+UniqueID+'&ver='+versionID;
    //     var url = BaseAPI.LoginUrl+this.state.phone+'&code='+this.state.code+paramsStr;
    //     fetch(url, {
    //         method:'GET'
    //     }).then((res)=>res.json())
    //         .then((json)=>{
    //             this.setState({showProgress:false});
    //             console.log('登录注册界面'+ json + JSON.stringify(json));
    //             if (json.state ===0){
    //
    //
    //                 // console.log('数据Key'+ json.)
    //                 this.refs.toast.show('登录成功');
    //                 StorageUtil.set('hasLogin',{'hasLogin':true});
    //                 StorageUtil.set('token',{'token':json.token});
    //
    //                 StorageUtil.set('token',{'token':json.token});
    //
    //
    //                 // StorageUtil.set('uid',{'uid':json.user.uid});
    //
    //                 const resetAction = NavigationActions.reset({
    //                     index: 0,
    //                     actions: [
    //                         NavigationActions.navigate({routeName: 'Home'})
    //                     ]
    //                 });
    //                 this.props.navigation.dispatch(resetAction);
    //
    //             }else {
    //                 this.refs.toast.show('登录失败');
    //             }
    //         })
    //         .catch((e)=>{
    //             console.log('网络请求'+e+ JSON.stringify(e));
    //
    //             this.setState({showProgress:false});
    //             // // 网络错误
    //             this.refs.toast.show('网络请求出错：' + e);
    //         })
    // }

    render() {
        return (
            <View style={styles.container}>
              <ScrollView>

                <View style={styles.logoViewStyle}>
                    <Image
                        style={styles.logoStyle}
                        source={require('../../images/login/ic_logo.png')}
                    />
                </View>

                {/*手机号*/}
                <View style={styles.titleViewStyle}>
                    <Image
                        style={styles.phoneIconStyle}
                        source={require('../../images/login/icon_phone.png')}
                    />
                    <TextInput
                        multiline={false}
                        placeholder='请输入手机号'
                        style={styles.detailStyle}
                        underlineColorAndroid="transparent"
                        onEndEditing={()=>{
                            if (!Utils.isPhoneAvailable(this.state.phone)){
                                this.refs.toast.show('手机号不正确');
                            }
                        }}
                        onChangeText={(text) => {
                            this.setState({phone: text.trim()})
                        }} />
                </View>
                <ListItemDivider/>

                {/*验证码*/}
                <View style={styles.titleViewStyle}>
                    <Image
                        style={styles.codeIconStyle}
                        source={require('../../images/login/icon_code.png')}
                    />
                    <View style={styles.codeViewStyle}>
                        <VerifyCode style={styles.detailStyle}
                                    placeholder='请输入验证码'
                                    placeholderTextColor='#b0afaf'
                                    countdownNormalStyle={styles.countdownNormalStyle}
                                    countdownStartStyle={styles.countdownStartStyle}
                                    countdownEndStyle={styles.countdownEndStyle}
                                    countdownNormalTextStyle={styles.countdownNormalTextStyle}
                                    countdownStartTextStyle={styles.countdownStartTextStyle}
                                    countdownEndTextStyle={styles.countdownEndTextStyle}
                                    maxTime={60}
                                    normalTxt='获取验证码'
                                    countdownTxt='S'
                                    endTxt='再次获取'
                                    auto={false}
                                    beforeCountdown={this.beforeCountdown}
                                    startCountdown={this.startCountdown}
                                    onValueChange={this.onValueChange}/>
                    </View>
                </View>

                <ListItemDivider/>

                  {/*<View style={styles.btnLogoViewStyle}>*/}
                      {/*<Image*/}
                          {/*style={styles.btnBgStyle}*/}
                          {/*source={require('../../images/login/btnlogo.png')}*/}
                      {/*/>*/}
                  {/*</View>*/}

                  <TouchableOpacity activeOpacity={1} onPress={this.goLogin.bind(this)}>
                      <LinearGradient colors={['#fe7133','#ff4114']} style={styles.linearGradient}>
                          <Text style={{color:'#fdfdfd',fontSize:14}}>登录</Text>
                      </LinearGradient>
                  </TouchableOpacity>

                {/*/!*登录*!/*/}
                {/*<TouchableOpacity activeOpacity={1} onPress={this.goLogin.bind(this)}>*/}
                    {/*<View style={styles.btnLogoViewStyle}>*/}
                        {/*<Image*/}
                            {/*style={styles.btnBgStyle}*/}
                            {/*source={require('../../images/login/btnlogo.png')}*/}
                        {/*/>*/}
                     {/*/!*<Text style={{color:'white',fontSize:16}}>登录</Text>*!/*/}
                    {/*</View>*/}
                {/*</TouchableOpacity>*/}

             </ScrollView>

                <Toast
                    ref="toast"
                    position='center'/>

                { this.state.showProgress ?
                    (<LoadingView cancel={() => this.setState({showProgress:false})}/>):(null)}

            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor:'white',
        flexDirection: 'column',
    },
    logoViewStyle:{
        marginTop:width/6,
        justifyContent:'center',
        alignItems:'center',
        backgroundColor:'white',
    },
    logoStyle:{
        height:0.56*247,
        width:0.56*247
    },
    titleViewStyle:{
        backgroundColor:'white',
        height:0.56*130,
        width:width,
        flexDirection:'row',
        justifyContent:'center',
        alignItems:'center'
    },
    codeViewStyle:{
        backgroundColor:'white',
        height:0.56*130,
        width:width-0.56*110,
        flexDirection:'row',
        justifyContent:'center',
        alignItems:'center'
    },
    phoneIconStyle:{
      height:0.56*38,
      width:0.56*30,
      marginLeft:0.56*80
    },
    btnLogoViewStyle:{
        marginTop:0.56*60,
        justifyContent:'center',
        alignItems:'center',
        backgroundColor:'white',
        // height:0.56*200,
        // // width:0.56*674,
        // // width:0.56*674,
        // // flex:1,
        // width:width-60,
        // marginLeft:30,
        // marginRight:30,
        // backgroundColor:'white',
        // justifyContent:'center',
        // alignItems:'center'
    },
    btnBgStyle:{
      // marginTop:0.56*60,
        // flex:1,
      height:0.56*80,
      width:0.56*450,
      // justifyContent:'center',
      //   alignItems:'center'
    },
    codeIconStyle:{
        height:0.56*35,
        width:0.56*37,
        marginLeft:0.56*80
    },
    loginViewStyle: {
        width:width-60,
        marginLeft:30,
        marginRight:30,
        marginTop:0.56*60,
        height:0.56*80,
        borderRadius: 5,
        backgroundColor: '#ff4114',
        justifyContent: 'center',
        alignItems: 'center'
    },
    linearGradient: {
        justifyContent:'center',
        alignItems:'center',
        height:0.56*70,
        marginLeft:0.56*40,
        marginRight:0.56*40,
        marginTop:0.56*40,
        borderRadius:0.56*20
    },
    detailStyle:{
        flex:1,
        marginLeft:0.65*24,
        fontSize:15,
        color:'#909090'
    }
});
